<?php
define('WX','WX');
define('H5','H5');

class employeeManage
{
	/* 
	 * 返回验证码是否有效
	*/
	public static function verify($code) { 
		$VerifyCode = M("module_verify_code");
		$condition['code'] = array('eq',$code);
		$result = $VerifyCode->where($condition)->find();
		if ($result) {
			
			return $result;
// 			if ($VerifyCode->where($condition)->getField('isClaim') == 0) {
// 				Output::instance()->resultCode(code_success);
// 				return code_success;
// 			} else {
// 				$msg = '奖品已领取';
// 				Output::instance()->resultCode(code_custom_error, $msg);
// 				return code_verifycode_claimed;
// 			}
		} else {
			$msg = '无效的验证码';
			Output::instance()->resultCode(code_custom_error, $msg);
			return code_verifycode_notexist;
		}
		
	}
	public static function searchSystem($employeeUId,$employeeUName,$type) {

		$result = array();
		//TODO::员工操作
		if(strcasecmp($type, 'verifyCode') == 0){
			$result['title'] = '验证码操作系统';
			$result['searchTitle'] = '验证码';
			$result['searchTip'] = '请输入验证码';
		}else if(strcasecmp($type, 'telMember') == 0){
			$result['title'] = '会员操作系统';
			$result['searchTitle'] = '会员手机号';
			$result['searchTip'] = '请输入会员手机号';

		}else if(strcasecmp($type, 'noMember') == 0){
			$result['title'] = '会员操作系统';
			$result['searchTitle'] = '会员编号';
			$result['searchTip'] = '请输入会员编号';
		}else if(strcasecmp($type, 'order') == 0){
			$result['title'] = '订单操作系统';
			$result['searchTitle'] = '订单编号';
			$result['searchTip'] = '请输入订单编号';
		}else if(strcasecmp($type, 'reserveOrder') == 0){
			$result['title'] = '订单操作系统';
			$result['searchTitle'] = '预订编号';
			$result['searchTip'] = '请输入预订编号';
		}
		Output::instance()->module('employeeManage', 'search_system')->object($result);
	}
	
	
	public static function searchVerifyCode($code,$employeeUId,$employeeUName) { 
		$VerifyCode = M("module_verify_code");
		$condition['code'] = array('eq',$code);
		$result = $VerifyCode->where($condition)->find();
		if ($result) {
			//TODO::添加员工操作记录
			Output::instance()->module('employeeManage', 'verifycode_info')->object($result);
		} else {
			$msg = '无效的验证码';
			Output::instance()->resultCode(code_custom_error, $msg);
		}
		
	}
	
	public static function getOrderInfo($serialNumber,$customerId){
		Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		Session::switchCustomer($customerId);
		$condition['serialNumber'] = array('eq',$serialNumber);
		$condition['fromCustomerId'] = array('eq',$customerId);

		$order = $OrderModel->where($condition)->find();
		if($order){

			$params = new stdClass();
			$params->id = $order['id'];
			$params->fromUserName = $order['fromUserName'];
			$result =  Module::callModule('product', NULL, 'getOrderInfo', $params);
			Output::instance()->module('employeeManage', 'order_info')->object($result);

		}else{
			$msg = '无效的订单编号';
			Output::instance()->resultCode(code_custom_error, $msg);
		}

		
	}
	
	public static function getReserveOrderInfo($serialNumber,$customerId){
		Session::switchCustomer(0);
		$StoreReserveModel = M("store_reserve");
		$condition['serialNumber'] = array('eq',$serialNumber);
// 		$condition['fromCustomerId'] = array('eq',$customerId);
		
		$reserve = $StoreReserveModel->where($condition)->find();
		
		if($reserve){
			$userInfo = get_UserInfo_by_fromUserName($reserve['fromUserName']);
			if($userInfo){
				$fullName = $userInfo['fullName'];
			}else{
				$fullName= NULL;
			}
			
			$params = new stdClass();
			$params->id = $reserve['id'];
			$params->fromUserName = $reserve['fromUserName'];
			$params->fullName = $fullName;
			$result =  Module::callModule('store', NULL, 'getStoreReserveOrder', $params);

			Output::instance()->module('employeeManage', 'reserve_order_info')->object($result);
			
		}else{
			$msg = '无效的预订编号';
			Output::instance()->resultCode(code_custom_error, $msg);
		}
		Session::switchCustomer($customerId);
		
	}
	
// 	public static function changeMemberScore(){
// 		$VerifyCode = M("module_verify_code");
// 		$condition['code'] = array('eq',$code);
// 		$result = $VerifyCode->where($condition)->find();
// 		if ($result) {
// 			//TODO::添加员工操作记录
// 			Output::instance()->module('employeeManage', 'verifycode_info')->object($result);
// 		} else {
// 			$msg = '无效的验证码';
// 			Output::instance()->resultCode(code_custom_error, $msg);
// 		}
// 	}
	
	public static function claim($code, $customerUserId) {
		$customerId = Session::$user['customerId'];
		$time = date("Y-m-d H:i:s");
		 Session::switchCustomer(0);
	    $OrderModel = M("module_product_order");
	    Session::switchCustomer($customerId);
		$VerifyCode = M("module_verify_code");
		$condition['code'] = array('eq',$code);
		$verifyCode = $VerifyCode->where($condition)->find();
		
		if ($verifyCode) {
			if($verifyCode['disabled']=="0") {
				$msg = '验证码不可用';
				Output::instance()->resultCode(1, $msg);
				return;
			}
			if($verifyCode['validate'] == 1){
				Log::write('enter herer');
				$validateEndTime = $verifyCode['validateEndTime'];
				if($validateEndTime != NULL){
					if(strtotime($time) >strtotime($validateEndTime)){
						$msg = '验证码已过期';
						R('EmployeeManage/addUserAction',
						array($customerId,$customerUserId,'sy','使用验证码',$code.'过期失败'));
						
						Output::instance()->resultCode(code_custom_error, $msg);
						return code_red_envelope_verify_code_has_expire;
					}
				}
			}
			
			$data['isClaim'] = 1;
			$data['customerUserId'] = $customerUserId;
			$data['claimTime'] = date('Y-m-d H:i:s');
			$ret = $VerifyCode->where($condition)->save($data);
			$codeWhere["oid"]=array('eq',$verifyCode['oid']);
			$codeWhere["isClaim"]=array("eq",0);
			$result = $VerifyCode->where($codeWhere)->select();
			if ($ret !== false) {
				if($verifyCode["oid"]) { //虚拟商品核销，更新订单状态为交易成功
					$oid=$verifyCode["oid"];
					$order=$OrderModel->where("id=$oid")->find();
					if(!$result){
						if($order['deliveryType']=='pickup'){
							$VerifyCode->query("update wx_module_product_order set status='deliveredtostore' where id=$oid");
						}else if($order['deliveryType']=='delivery'){
							$VerifyCode->query("update wx_module_product_order set status='delivered' where id=$oid");
						}
						R("Product/myqupdateDividents",array($oid));
					}
					if($order) {
						//发送消息
						$fromUserName=$order["fromUserName"];
						$text.="您购买的".$verifyCode["reward"]."电子券验证码:".$code."已经使用！\n";
						$text.="使用日期：".date ("Y年m月d日")."\n";
						WeixinApi::sendText($fromUserName,$text);
					}
				}
			
				R('EmployeeManage/addUserAction',
				array($customerId,$customerUserId,'sy','使用验证码',$code));
				
				
				Output::instance()->resultCode(code_success);
				return code_success;
			} else {
				$msg = '领取失败';
				R('EmployeeManage/addUserAction',
				array($customerId,$customerUserId,'sy','使用验证码',$code.'失败'));
				
				
				Output::instance()->resultCode(code_custom_error, $msg);
				return code_verifycode_claimed;
			}
		} else {
			$msg = '无效的验证码';
			
			R('EmployeeManage/addUserAction',
			array($customerId,$customerUserId,'sy','使用验证码',$code.$msg));
			
			Output::instance()->resultCode(code_custom_error, $msg);
			return code_verifycode_notexist;
		}
	}
	
	public static function manageSystem(){
		Output::instance()->module('employeeManage', 'login_system')->object('');
	}
	
	public static function login($email,$password){
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		
		// 切换客户
		
		$CustomerUser = M("customer_user");
		$conditionPsw['email'] = array('eq', trim($email));
		$conditionPsw['password'] = array('eq', Encryption::password(trim($password)));
		$conditionPsw['customerId'] = array('eq',$customerId);
		$conditionName['agent'] = array('eq','service');
		$resultUser = $CustomerUser->where($conditionPsw)->find();
		Log::write($CustomerUser->getlastsql());
		if(!isset($resultUser)){
			Output::instance()->resultCode(code_sql_error,'登录名或密码错误');
		}else{

			$user = array();
			$user['fullName'] = $resultUser['fullName'];
			$user['id'] = $resultUser['id'];
			
			R('EmployeeManage/addUserAction',
			array($customerId,$resultUser['id'],'登录','登录终端查询系统',$resultUser['fullName']));
			
			Output::instance()->module('employeeManage', 'action_system')->object($user);
		}
		Session::switchCustomer($customerId);
		
		//Session::switchCustomer($cid);
	}
	public static function fakelogin(){
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		
		$resultUser = array();
		$resultUser['id'] = 70;
		Output::instance()->module('employeeManage', 'action_system')->object($resultUser);
		Session::switchCustomer($customerId);
		
		//Session::switchCustomer($cid);
	}
	public static function actionSystem(){
		$customerId = Session::$user['customerId'];
		Output::instance()->module('employeeManage', 'action_system')->object('');
		
		
		//Session::switchCustomer($cid);
	}
	//密友圈员工后台首页
    public static function index($id,$fromType){
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
        $userId = Session::$user['userId'];
        Session::switchCustomer(0);
        $customerUser = M("customer_user");
		$employee_table = M('employee_terminal_config');
        Session::switchCustomer($customerId);
		$user_table = M('user');
        $where["a.agent"]=array("eq","service");
        $where["a.customerId"]=array("eq",$customerId);
        if($id){
            $where["a.storeId"]=array("eq",$id);
        }
		if($fromType == 'H5'){
			$phone = $user_table->where(['id' => $userId])->getField('phone');
			$where["a.phone"]=array("eq",$phone);
			$miUserInfo['qId'] = '';
			$miUserInfo['isSaleSource'] = 1;
			$miUserInfo['signSaleSource'] = 1;
		}else{
			$where["a.openid"]=array("eq",$userName);
			//密友圈是否标记自动销售源返回到前端
			$miUserInfo = $user_table->alias('a')
				->join('inner join wx_quan_user b on b.uid=a.id')
				->join('inner join wx_miyouquan c on c.id=b.qid')
				->where(['a.userName'=>$userName, 'b.deleted'=>0, 'c.cId'=>$customerId])
				->field('b.qId,b.isSaleSource,c.signSaleSource')
				->find();
		}

	    $result = $customerUser->alias("a")
            ->join("wx_".$customerId."_user_weixin_info b on a.openid=b.openid")
			->join('left join wx_employee_terminal_config e on a.customerId=e.cId')
            ->where($where)
            ->field("a.id, a.storeId,a.storeName,b.nickname,b.headimgurl,e.themeColor, e.themeImg,e.homePageImg,e.menuJson")
            ->find();
		//var_dump($customerUser->getLastSql());exit;
        if(isNativeApp()){
            $phone = $user_table->where(['id' => $userId])->getField('phone');
            unset($where['a.openid']);
            $where["a.phone"]=array("eq",$phone);
            $result = $customerUser->alias("a")
                ->join("wx_".$customerId."_user b on a.phone=b.phone")
                ->join('left join wx_employee_terminal_config e on a.customerId=e.cId')
                ->where($where)
                ->field("a.id, a.storeId,a.storeName,b.fullName,b.profileUrl,e.themeColor, e.themeImg,e.homePageImg,e.menuJson")
                ->find();
        }





	    if(!$result){
			$result = $employee_table->where(['cId'=>$customerId,'delete'=>0])->find();
			if(!$result){
				$result = [];
			}
			if(!$result['themeImg']){
				$result['themeImg'] = 'http://oss.mboxone.com/20171126/image/3/1511710718735480.jpg';
			}
			if(!$result['homePageImg']){
				$result['homePageImg'] = 'http://oss.mboxone.com/20171126/image/3/1511710723754555.jpg';
			}
	        Output::instance()->module("employeeManage","login")->object($result);
        }else{
			//给默认值
			if(!$result['themeImg']){
				$result['themeImg'] = 'http://oss.mboxone.com/20171126/image/3/1511710718735480.jpg';
			}
			if(!$result['homePageImg']){
				$result['homePageImg'] = 'http://oss.mboxone.com/20171126/image/3/1511710723754555.jpg';
			}

			$result['qId'] = $miUserInfo['qId']?$miUserInfo['qId']:'';
			$result['isSaleSource'] = $miUserInfo['isSaleSource']?$miUserInfo['isSaleSource']:0;
			$result['signSaleSource'] = $miUserInfo['signSaleSource']?$miUserInfo['signSaleSource']:'';
			if($result['menuJson']){
				$result['menuJson'] = json_decode($result['menuJson'], true);
				$menuArr = [];
				foreach($result['menuJson'] as $k=>$v){
					if(!$v['isShow']){
						continue;
					}
					$menuArr[$k] = $v;
				}
				$result['menuJson'] = $menuArr;
				//不存在qid
				if(!$miUserInfo['qId']){
					unset($result['menuJson'][1]);
				}
				if(!$miUserInfo['isSaleSource']){
					unset($result['menuJson'][2]);
					unset($result['menuJson'][3]);
				}
				if(!$result['storeId']){
					unset($result['menuJson'][0]);
				}
				$result['new_server_host'] = C('NEWSERVER_NAME');
			}

			$result['cid'] = $customerId;
            Output::instance()->module("employeeManage","index")->object($result);
        }

    }
    //密友圈员工后台登陆绑定微信
    public static function binding($email,$password){
        $customerId = Session::$user['customerId'];
        $userName = Session::$user['userName'];
		$userId = Session::$user['userId'];
        Session::switchCustomer(0);
        // 切换客户
		$media_tab = M('ind_media_info');
        $CustomerUser = M("customer_user");
		$quanModel=M("quan_user");
		$miyouquanModel=M("miyouquan");
		Session::switchCustomer($customerId);

		$user = M('user');

		$conditionName['customerId'] = array('eq',$customerId);
		$conditionName['agent'] = array('eq','service');
		/*用户只能绑定一个账号,排除首次登陆成功后退再次登录别的账号*/
		$conditionName['openid'] = array('eq',$userName);
		$retUser = $CustomerUser->where($conditionName)->find();
		if($retUser){
			if(($retUser['email'] == $email) && ($retUser['password'] == Encryption::password(trim($password)))){
				Output::instance()->object($retUser);
				return;
			}else{
				Output::instance()->object([
					'code'=>1,
					'msg'=>'登录名或者密码错误'
				]);
				return;
			}

		}
		unset($conditionName['openid']);
		$conditionPsw['customerId'] = array('eq',$customerId);
        $conditionPsw['email'] = array('eq', trim($email));
        $conditionPsw['password'] = array('eq', Encryption::password(trim($password)));

        $resultUser = $CustomerUser->where($conditionPsw)->find();
        if(!isset($resultUser)){
            Output::instance()->resultCode(code_sql_error,'登录名或密码错误');
			return;
        }else if($resultUser['openid']){
			Output::instance()->resultCode(code_sql_error,'此账号已被他人绑定,无法重复绑定');
			return;
		}else{

            if (isMicroMessengerUserAgent()) {
				//绑定微信组
				$groupRet = true;
				if($resultUser['groupId']){
					$mediaId = $media_tab->where(['cid'=>$customerId, 'deleted'=>0, 'isDefault'=>0])->field('id')->find();
					$groupRet = R('User/removeNewUsersToGroup',
						array($mediaId, $userId, $resultUser['groupId'],1));
				}

				//绑定密友圈
				$quanRet = true;
				if($resultUser['qid']){
					//是否在其他圈
					$quanId = $quanModel->alias('a')
						->join('inner join wx_miyouquan b on a.qid = b.id')
						->where(['a.uid'=>$userId, 'b.cId'=>$customerId, 'a.deleted'=>0,'a.status'=>1])
						->getField('b.id');

					if($quanId && ($resultUser['qid'] == $quanId)){
						$quanRet = true;
					}else if($quanId){
						$quanRet = false;
					}else{
						$params = new stdClass();
						$params->userName = $userName;
						$params->qId = $resultUser['qid'];
						$signSaleSource = $miyouquanModel->where(['id' => $resultUser['qid']])->getField('signSaleSource');
						$params->signSaleSource = $signSaleSource;
						$params->backend = 1;
						$params->uid = $userId;
						Module::callModule('quan',null,'subscribeRegQuanUser',$params);
						$quanRet = true;
					}
				}

                $wxRet = $CustomerUser->where("id=" . $resultUser['id'])->setField("openid", $userName);

				if($groupRet==false || $quanRet==false || !is_numeric($wxRet)){
					Log::write('jie-----员工绑定结果groupRet:'.$groupRet.'|quanRet:'.$quanRet.'|wxRet:'.$wxRet);
				}
				/*首次绑定时,将wx_customer_user中的用户信息复制到wx_3_user中 jie*/
				if($user->where(['userName'=>$userName])->find()){
					$user->where(['userName'=>$userName])->save([
						'fullName'=>$resultUser['fullName'],
						'phone'=>$resultUser['phone']
					]);
				}
				//将登录信息保存起来
                R('EmployeeManage/addUserAction',
                    array($customerId,$resultUser['id'],'登录','登录密友圈员工后台管理系统',$resultUser['fullName']));
            }
            Output::instance()->object($resultUser);
        }

    }
    //门店订单页面
    public static function storeOrder($storeId){
        $result["id"]=$storeId;
        Output::instance()->module("employeeManage","order")->object($result);
    }

	/**
	 * 门店订单数据
	 * @param $storeId		/商店id
	 * @param null $name	/搜索条件
	 * @param int $status	/订单状态
	 * @param int $start	/分页起始
	 * @param int $limit	/偏移量
	 */
    public static function storeOrderList($storeId,$name=null,$status=0,$start=0,$limit=10){
        $customerId = Session::$user['customerId'];
		$uid = Session::$user["userId"];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        $orderDetailodel = M("module_product_order_detail");
        Session::switchCustomer($customerId);
        if($name){
            $condition['_logic'] = 'OR';
            $condition["b.name"]=array("like",'%'.$name.'%');
            $condition["a.fullName"]=array("like","%".$name."%");
            $condition["a.phone"]=array("like","%".$name."%");
            $condition["a.serialNumber"]=array("like","%".$name."%");
            $where["_complex"]=$condition;
        }
		$tempWhere = "a.storeResourceId = $storeId";
		$uid?$tempWhere.=" or a.saleSource=$uid":"";
		$where["_complex"] =$tempWhere;
        $where['a.fromCustomerId']=array("eq",$customerId);
        switch($status){
            case 0:
                $where['a.status']=array("eq",'deliveringtostore');
                break;
            case 1:
                $where['a.status']=array("eq",'deliveredtostore');
                break;
            case 2:
                $where['a.status']=array("eq",'ok');
                break;
            case 3:
                $where['a.status']=array(array("eq",'refund'),array("eq",'refundedpart'),"or");
                break;
        }
        $start = $start*$limit;
        $arr = $orderModel->alias("a")
            ->join("inner join wx_module_product_order_detail b on a.id=b.oid")
            ->where($where)
            ->limit($start,$limit)
            ->order("payTime desc")
            ->field("a.id,a.status,a.payTime")
            ->group("a.id")
            ->select();
        if(!$arr){
            Output::instance()->resultCode();
            return;
        }
        $count = $orderModel->alias("a")
            ->join("inner join wx_module_product_order_detail b on a.id=b.oid")
            ->where($where)->field("a.id")->group("a.id")->select();
        $count = count($count);
        foreach($arr as $key=>$value){
            $oid = $value['id'];
            $detailInfo = $orderDetailodel->where("oid=$oid")->field("name,picUrl1,picUrl,price")->select();
            $arr[$key]['detail']=$detailInfo;
        }
        Output::instance()->objArray($arr,$count);
    }
	//门店订单详情
    public static function orderDetail($oid){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        $orderDetailModel = M("module_product_order_detail");
        Session::switchCustomer($customerId);
        $result = $orderModel->alias("a")
            ->join("wx_".$customerId."_user_weixin_info b on a.fromUserName=b.openid")
            ->where("a.id=$oid")
            ->field("a.id,a.deliveryType,a.storeResourceName,a.remark,a.fullName,a.phone,a.address,a.price,a.status,a.serialNumber,a.payTime,b.nickname,b.headimgurl")->find();
        $detailInfo = $orderDetailModel->alias("a")
            ->join("wx_module_product_order_detail_specification b on a.id=b.did")
            ->where("a.oid=$oid")
            ->field("a.name,a.picUrl1,price,a.count,b.firstSpecificName,b.secSpecificName")
            ->select();
        foreach($detailInfo as $key=>$value){
            if($value['picUrl1']){
                $value['picUrl1']=json_decode($value['picUrl1'],true);
                if(count($value['picUrl1'])>1){
                    $detailInfo[$key]['picUrl1'] = $value['picUrl1'][1];
                }else{
                    $detailInfo[$key]['picUrl1'] = $value['picUrl1'][0];
                }
            }
        }
        $result['detail']=$detailInfo;
        Output::instance()->module("employeeManage","orderDetail")->object($result);
    }
    //修改状态为已配送到门店以及交易完成
    public static function updateOrder($oid, $pCode = '', $cUserId){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        $customerUser = M("customer_user");
        Session::switchCustomer($customerId);
        $resultUser = $customerUser->where(['id' => $cUserId])->field("id,fullName")->find();
		$orderInfo = $orderModel->where(['id' => $oid])->find();
        $status = $orderInfo['status'];
        if ($status != 'deliveringtostore' && $status != 'deliveredtostore') {
            Output::instance()->object([
				'code' => 1,
				'msg' => '该状态不可修改'
			]);
            return;
        }
        if($status=='deliveringtostore'){
            $res = R("Product/updateOrderTipByOrderId",array($oid,null,null,'deliveredtostore', null, null, null, 1));
        }else{
			/*门店自提需要验证自提码*/
			if ($orderInfo['deliveryType'] == ORDER_DELIVERYTYPE_PICKUP) {
				$pickupCode = $orderInfo['pickupCode'];
				if ($pCode != $pickupCode) {
					Output::instance()->object([
						'code' => 5,
						'msg' => '自提码错误'
					]);
					return;
				}
			}
            $res = R("Product/updateOrderTipByOrderId",array($oid,null,null,'ok', null, null, null, 1));
        }
		if ($res) {
			Output::instance()->object([
				'code' => 0,
				'mag' => 'ok'
			]);
		} else {
			Output::instance()->object([
				'code' => 0,
				'mag' => '更改状态失败'
			]);
			return;
		}
        $result = R('EmployeeManage/addUserAction',
                array($customerId,$resultUser['id'],'更新订单',$resultUser['fullName'],'修改订单状态'));

    }

	/**
	 * 获取员工作为销售源订单,如果不是销售源,终端不显示订单按钮
	 * @param null $search	/搜索
	 * @param int $status	/订单状态0:组团中1:待发货2:已发货3:已完成4:退款单
	 * @param int $start	/分页
	 * @param int $limit
	 * @param int $type		/0:普通点单 1表单订单
	 */
	public static function getSaleSourceOrderList($search=null,$status=0,$start=0,$limit=10,$type=0){
		$cId = Session::$user['customerId'];
		$userId = Session::$user['userId'];
		Session::switchCustomer(0);
		$miQuanUser_table = M('quan_user');
		$order_table = M('module_product_order');
		$orderDte_table = M('module_product_order_detail');
		Session::switchCustomer($cId);
		$where = $condition = $arr2 = [];
		if($search && $type != 1){
			$condition['_logic'] = 'OR';
			$condition['b.name'] = ['lick', '%'.$search.'%'];
			$condition['a.fullName'] = ['lick', '%'.$search.'%'];
			$condition['a.phone'] = ['lick', '%'.$search.'%'];
			$condition['a.serialNumber'] = ['lick', '%'.$search.'%'];
			$where['_complex'] = $condition;
		}else if(!empty($search)){
			$where['a.serialNumber'] = $search;
		}
		//$where['a.storeResourceId'] = $storeId;
		$where["a.deleted"]=array('eq',0);
		if($type == 1){
			$where["a.type"] = ORDER_TYPE_FORM;
		}else{
			$where["a.type"] = ['neq', ORDER_TYPE_FORM];
		}
		$where["a.fromCustomerId"]=array('eq',$cId);
		switch($status){
			case 0://组团中
				$where["a.status"]=["eq",'teaming'];
				break;
			case 1://等待发货或待配送到门店
				if($type == 1){
					$where["a.status"]=array(array("eq",order_status_delivering),array("eq",order_status_submission),"or");
				}else{
					$where["a.status"]=array(array("eq",order_status_delivering),array("eq",order_status_deliveringtostore),array("eq",order_status_ordersign),array("eq","supported"),"or");
				}
				break;
			case 2://已发货或已配送到门店
				$where["a.status"]=array(array("eq",order_status_delivered),array("eq",order_status_deliveredtostore),"or");
				break;
			case 3://已完成或已确认报名
				$where["a.status"]=array(array("eq",order_status_ok),array("eq",order_status_confirmsign),'or');
				break;
			case 4://退款中或部分退款或已退款
				$where["_string"] ="a.status='".order_status_refund."' or a.status='".ORDER_STATUS_REFUNDEDPART."' or a.status='".ORDER_STATUS_REFUNDING."'";
				break;
			case 5:
				$where['a.status'] = order_status_cancel;
				break;
		}

		$quanInfo = $miQuanUser_table->alias('a')
			->join('inner join wx_miyouquan b on b.id=a.qid')
			->where(['a.uid'=>$userId, 'a.deleted'=>0, 'b.cId'=>$cId])
			->field('a.isSaleSource')
			->find();
		if(!$quanInfo['isSaleSource']){
			Output::instance()->object([
				'code'=>-1,
				'msg'=>'不是销售源'
			]);
			return;
		}
		//如果是销售源
		$where['a.saleSource'] = $userId;

		//获取订单详情
		$orderList = $order_table->alias('a')
			->join("inner join wx_module_product_order_detail b on a.id=b.oid")
			->where($where)
			->order('a.createTime desc')
			->limit($start, $limit)
			->field('a.id,a.serialNumber, a.status, a.payTime,a.price, b.name,b.saleCut,a.createTime, b.isMiUserCut')
			->group('a.id')
			->select();
		Log::write('jie----dingdansql'.$order_table->getLastSql());
		if($orderList == null){
			Output::instance()->object([
				'total'=>0,
				'results'=>[]
			]);
			return;
		}

		$count = $order_table->alias('a')
			->join("inner join wx_module_product_order_detail b on a.id=b.oid")
			->where($where)
			->field('a.id')
			->group('a.id')
			->select();
		$count = count($count);
		Log::write('jie----dingdansql'.$order_table->getLastSql());
		if($orderList && $type!=1){
			foreach($orderList as $k=>$v){
				$orderDet = $orderDte_table->where(['oid'=>$v['id']])->field('name, picUrl, picUrl1, price')->select();
				$orderList[$k]['productList'] = $orderDet;
			}
		}
		//获取订单详情
		Output::instance()->objArray($orderList,$count);
	}

	/**
	 * 销售源订单详情
	 * @param $oid /订单id
	 */
	public static function saleSourceOrderDetail($oid){
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$order_table = M('module_product_order');
		$orderDte_table = M('module_product_order_detail');
		Session::switchCustomer($cid);
		$wexinUser_tab = M('user_weixin_info');
		$orderInfo = $order_table->alias('a')
			->join('wx_'.$cid.'_user_weixin_info b on a.fromUserName=b.openid')
			->where(['a.id'=>$oid])
			->field('a.id,a.miUid,a.deliveryType,a.storeResourceName,a.createTime,a.remark,a.payType,a.fullName,a.phone,a.address,a.price,a.status,a.serialNumber,a.payTime,b.nickname,b.headimgurl')
			->find();
		$detailInfo = $orderDte_table->alias("a")
			->join("wx_module_product_order_detail_specification b on a.id=b.did")
			->where("a.oid=$oid")
			->field("a.name,a.picUrl1,a.picUrl,a.price,a.saleCut,a.count,b.firstSpecificName,b.secSpecificName,a.customizedInfo")
			->select();
		$orderInfo['buyUser']['nickname'] = $orderInfo['nickname'];
		$orderInfo['buyUser']['headimgurl'] = $orderInfo['headimgurl'];
		$orderInfo['buyUser']['phone'] = $orderInfo['phone'];
		$orderInfo['buyUser']['fullName'] = $orderInfo['fullName'];
		unset($orderInfo['nickname']);
		unset($orderInfo['headimgurl']);
		unset($orderInfo['phone']);
		unset($orderInfo['fullName']);
		foreach($detailInfo as $key=>$value){
			if($value['picUrl1']){
				$value['picUrl1']=json_decode($value['picUrl1'],true);
				if(count($value['picUrl1'])>1){
					$detailInfo[$key]['picUrl1'] = $value['picUrl1'][1];
				}else{
					$detailInfo[$key]['picUrl1'] = $value['picUrl1'][0];
				}
			}
			$detailInfo[$key]['specific'][] = ['name'=>$value['firstSpecificName']];
			$detailInfo[$key]['specific'][] = ['name'=>$value['secSpecificName']];
			if(empty($value['firstSpecificName']) && empty($value['secSpecificName'])){
				$detailInfo[$key]['specific'] = [];
			}
			//定制信息
			if($value['customizedInfo']){
				$detailInfo[$key]['customizedInfo'] = json_decode($value['customizedInfo']);
			}
		}
		//查询分享人的信息
		$miUserInfo = [];
		if($orderInfo['miUid'] && ($orderInfo['miUid'] !== $orderInfo['uId'])){
			$miUserInfo = $wexinUser_tab->where(['userId'=>$orderInfo['miUid']])->field('nickname,headimgurl')->find();
		}
		$orderInfo['miUser']['nickName'] = $miUserInfo['nickname'];
		$orderInfo['miUser']['headImgUrl'] = $miUserInfo['headimgurl'];
		$orderInfo['productList']=$detailInfo;
		$orderInfo['type']='saleSource';
		Output::instance()->module("employeeManage","orderDetail")->object($orderInfo);
	}
}